package down.sallai.ml.controller;

import down.sallai.ml.bean.WxVerificationBean;
import down.sallai.ml.util.Constants;
import down.sallai.ml.util.R;
import down.sallai.ml.util.wx.EventDispatcher;
import down.sallai.ml.util.wx.GithubVerity;
import down.sallai.ml.util.wx.MessageUtil;
import down.sallai.ml.util.wx.MsgDispatcher;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Map;

/**
 * @description: $
 * @author: sallai
 * @time: 2022年1月4日 0004 下午 10:02:17 秒
 */
@Controller
@Slf4j
@RequestMapping("/wxapi")
public class WxAPIController {

    @Value("${wx.token}")
    private String token;

    @Autowired
    MsgDispatcher msgDispatcher;

    @Autowired
    RedisTemplate redisTemplate;

    @GetMapping("/verity")
    @ResponseBody
    public String verificationSource(WxVerificationBean bean){
        String[] str = { token, bean.getTimestamp() , bean.getNonce() };
        Arrays.sort(str); // 字典序排序
        String bigStr = str[0] + str[1] + str[2];
        // SHA1加密
        String digest = DigestUtils.sha1Hex(bigStr).toLowerCase();
        log.info("local:"+digest+" remote:"+bean.getSignature());
        // 确认请求来至微信
        if (digest.equals(bean.getSignature())) {
            return bean.getEchostr();
        }else{
            return "";
        }
    }

    @PostMapping("/verity")
    @ResponseBody
    public String recvTextMessage(HttpServletRequest request,HttpServletResponse response){
        log.info("接收到wx请求消息");
        String msg = "";
        try {
            Map<String, String> messageMap = MessageUtil.parseXml(request);
            log.info("消息内容->"+messageMap.get("Content"));
            String type = messageMap.get("MsgType");
            if(MessageUtil.REQ_MESSAGE_TYPE_EVENT.equals(type)){
                //事件处理
                log.info("wx user event handler");
                msg = EventDispatcher.processEvent(messageMap);
            }else {
                log.info("wx user info handler");
                request.setCharacterEncoding("UTF-8");
                response.setCharacterEncoding("UTF-8");
                //消息处理
                msg = msgDispatcher.processMessage(messageMap);

            }
            return msg;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";

    }

    @PostMapping("/verity/code")
    @ResponseBody
    public String verityCode(String code,HttpServletRequest request){
        if("".equals(code) && code.length() != GithubVerity.CODE_LEN) return new R().setMsg("验证码不符合规范").setCode(Constants.CODE_HAVE_ERR).toString();
        Object o = redisTemplate.opsForValue().get(code);
        if( null != o ) {
            request.getSession().setAttribute("github",true);
            return new R().setMsg("验证成功，畅游github吧！").setCode(Constants.CODE_SUCCESE).toString();
        }else {
            return new R().setMsg("验证失败！code不存在").setCode(Constants.CODE_HAVE_ERR).toString();
        }


    }

    @GetMapping("/verity/page")
    public String verityPage() {
        log.info("进入验证页面");
        return "wxVerity";
    }

}
